package com.tanhua.management.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.ManageCommentApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.management.mapper.UserInfoMapper;
import com.tanhua.management.pojo.UserInfo;
import com.tanhua.management.vo.CommentsVo;
import com.tanhua.management.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author why
 */
@Service
public class ManageCommentService {

    @Reference(version = "1.0.0")
    private ManageCommentApi manageCommentApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public PageResult queryComments(Integer page, Integer pageSize, String sortProp, String sortOrder, String publishId) {

        PageResult pageResult =new PageResult();

        PageInfo<Comment> pageInfo = manageCommentApi.queryComments(page, pageSize, sortProp, sortOrder, publishId);

        //返回了动态的消息信息，但是
        if (pageInfo==null){
            return null;
        }
        List<Comment> records = pageInfo.getRecords();
        //评论人的 昵称 评论人的id  这条消息的id 评论的内容 评论时间

        List<Long> userIds=new ArrayList<>();
        for (Comment record : records) {
            userIds.add(record.getUserId());
        }
        //将评论人的id 集合拿到，查询基本信息

        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.in("user_id",userIds);
        List<UserInfo> userInfos = this.userInfoMapper.selectList(wrapper);

        //封装一个集合 将数据进行封装
        List<CommentsVo> commentsVoList=new ArrayList<>();
        //双重遍历将其封装

        for (Comment record : records) {
            CommentsVo commentsVo=new CommentsVo();
                //遍历信息，将匹配的信息封装
            for (UserInfo userInfo : userInfos) {
                if (record.getUserId().intValue()==userInfo.getId().intValue()){

                    commentsVo.setContent(record.getContent());
                    commentsVo.setId(record.getId().toHexString());
                    commentsVo.setCreateDate(record.getCreated().intValue());
                    commentsVo.setNickname(userInfo.getNickName());
                    commentsVo.setUserId(userInfo.getId());
                    commentsVoList.add(commentsVo);
                }break;
            }
        }

        pageResult.setPages(page);
        pageResult.setPageSize(pageSize);
        Integer pages=(pageInfo.getTotal() / pageSize) +1;
        pageResult.setPage(pages);
        pageResult.setCounts(pageInfo.getTotal());
        pageResult.setItems(commentsVoList);
        return pageResult;
    }



}
